package com.wannengbang.cloudleader.homepage;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.codingending.popuplayout.PopupLayout;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.DeviceUnifyListBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.dialog.ApplyPlusDialog;
import com.wannengbang.cloudleader.dialog.ApplyRateDialog;
import com.wannengbang.cloudleader.dialog.ApplyRedEnvelopesDialog;
import com.wannengbang.cloudleader.dialog.ApplyVipDialog;
import com.wannengbang.cloudleader.dialog.ApplyVipPlusDialog;
import com.wannengbang.cloudleader.dialog.GiveAgentDialog;
import com.wannengbang.cloudleader.dialog.SetPlusRateDialog;
import com.wannengbang.cloudleader.event.ScanEvent;
import com.wannengbang.cloudleader.homepage.adapter.MachinesListAdapter;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 机具列表
 */
public class MachinesListActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_give)
    LinearLayout llGive;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;

    @BindView(R.id.iv_check)
    ImageView ivCheck;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.tv_apply_plus)
    TextView tvApplyPlus;

    @BindView(R.id.tv_implement_operation)
    TextView tv_implement_operation;

    private IHomePageModel homePageModel;
    private List<DeviceUnifyListBean.DataBean.ItemListBean> beanList;
    private MachinesListAdapter listAdapter;
    private int page = 1;
    private SkeletonScreen skeletonScreen;
    private String type;
    private String status;
    private String keyword = "";
    private String child_agent_id = "";
    private String agent_id = "";
    private String agent_name = "";
    private String is_send = "";
    private boolean allSelect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machines_list);
        ButterKnife.bind(this);
        initView();
        initData();
        setEvent();
    }

    private void setEvent() {
        tv_implement_operation.setOnClickListener(v -> {
            initImplementOperationDialog();
        });
    }

    private void initImplementOperationDialog() {
        //2.使用View作为弹出布局的内容
        View layout = View.inflate(this, R.layout.dialog_implement_operation_layout, null);

        TextView tvApplyRate = layout.findViewById(R.id.tv_apply_rate);
        TextView tvApplyVip = layout.findViewById(R.id.tv_apply_vip);
        TextView tvApplyPlus = layout.findViewById(R.id.tv_apply_plus);
        TextView tvApplyVipPlus = layout.findViewById(R.id.tv_apply_vip_plus);
        TextView tvApplyRedEnvelopes = layout.findViewById(R.id.tv_apply_red_envelopes);
        TextView tvGiveAgent = layout.findViewById(R.id.tv_give_agent);
        TextView tvGiveStore = layout.findViewById(R.id.tv_give_store);


        final PopupLayout popupLayout = PopupLayout.init(this, layout);
        //暂时
        tvApplyRedEnvelopes.setVisibility(View.VISIBLE);

        //0未激活 1已激活
        if ("0".equals(status)) {
            if (agent_id.equals(child_agent_id)) {
                tvApplyVipPlus.setVisibility(View.GONE);
                //设置费率
                tvGiveAgent.setVisibility(View.GONE);
                //申请费率(综合/高端)
                tvApplyRate.setVisibility(View.VISIBLE);
                if ("1".equals(type)) {
                    tvApplyVip.setText("申请设置Vip");
                    tvApplyVip.setVisibility(View.VISIBLE);
                    tvApplyPlus.setText("申请设置Plus");
                    tvApplyPlus.setVisibility(View.VISIBLE);
                } else if ("2".equals(type)) {
                    tvApplyVip.setVisibility(View.GONE);
                    tvApplyPlus.setVisibility(View.GONE);
                } else if ("3".equals(type)) {
                    tvApplyVip.setText("申请设置普通");
                    tvApplyVip.setVisibility(View.VISIBLE);
                    tvApplyPlus.setVisibility(View.GONE);
                    tvApplyVipPlus.setText("申请设置Plus");
                    tvApplyVipPlus.setVisibility(View.VISIBLE);

                } else if ("4".equals(type)) {
                    tvApplyVip.setVisibility(View.GONE);
                    tvApplyPlus.setText("申请设置普通");
                    tvApplyPlus.setVisibility(View.VISIBLE);
                    tvApplyVipPlus.setText("申请设置Vip");
                    tvApplyVipPlus.setVisibility(View.VISIBLE);
                    tvGiveAgent.setVisibility(View.VISIBLE);
                    //申请费率(综合/高端)
                    tvApplyRate.setVisibility(View.GONE);
                }
                //划拨给合伙人
                tvGiveStore.setVisibility(View.GONE);
            }
        } else if ("1".equals(status)) {
            if (agent_id.equals(child_agent_id)) {
                //申请费率(综合/高端)
                tvApplyRate.setVisibility(View.VISIBLE);
                //申请plus
                tvApplyPlus.setVisibility(View.GONE);
                //申请vip
                tvApplyVip.setVisibility(View.GONE);
                //设置费率
                tvGiveAgent.setVisibility(View.GONE);
                //划拨给合伙人
                tvGiveStore.setVisibility(View.VISIBLE);
                if ("4".equals(type)) {
                    //设置费率
                    tvGiveAgent.setVisibility(View.VISIBLE);
                    //申请费率(综合/高端)
                    tvApplyRate.setVisibility(View.GONE);
                }
            }

            if ("5".equals(type)||"6".equals(type)){

                tvApplyRedEnvelopes.setVisibility(View.GONE);
                tvApplyRate.setVisibility(View.GONE);

            }

        }

        List<String> device_no_list = new ArrayList<>();
        List<String> store_number_list = new ArrayList<>();
        for (DeviceUnifyListBean.DataBean.ItemListBean itemListBean : beanList) {
            if (itemListBean.isCheck()) {
                device_no_list.add(itemListBean.getNo());
                store_number_list.add(itemListBean.getMem_no());
            }
        }


        tvApplyRate.setOnClickListener(v -> {
            ApplyRateDialog rateDialog = ApplyRateDialog.newInstance(type, device_no_list);
            rateDialog.show(getSupportFragmentManager(), "rateDialog");
            rateDialog.setOnCallBackListener(() -> {

            });
            popupLayout.dismiss();
        });

        tvApplyVip.setOnClickListener(v -> {
            ApplyVipDialog vipDialog = ApplyVipDialog.newInstance(type, device_no_list);
            vipDialog.show(getSupportFragmentManager(), "vipDialog");
            vipDialog.setOnCallBackListener(() -> {
                refreshData();
            });
            popupLayout.dismiss();
        });

        tvApplyPlus.setOnClickListener(v -> {
              ApplyPlusDialog plusDialog = ApplyPlusDialog.newInstance(type, device_no_list);
              plusDialog.show(getSupportFragmentManager(), "plusDialog");
              plusDialog.setOnCallBackListener(() -> {
                  refreshData();
              });
            popupLayout.dismiss();
        });
        tvApplyVipPlus.setOnClickListener(v -> {
            ApplyVipPlusDialog vipPlusDialog = ApplyVipPlusDialog.newInstance(type, device_no_list);
            vipPlusDialog.show(getSupportFragmentManager(), "vipPlusDialog");
            vipPlusDialog.setOnCallBackListener(() -> {
                refreshData();
            });
            popupLayout.dismiss();
        });
        tvApplyRedEnvelopes.setOnClickListener(v -> {
            ApplyRedEnvelopesDialog vipPlusDialog = ApplyRedEnvelopesDialog.newInstance(type, device_no_list);
            vipPlusDialog.show(getSupportFragmentManager(), "RedEnvelopesDialog");
            vipPlusDialog.setOnCallBackListener(() -> {
                refreshData();
            });
            popupLayout.dismiss();
        });
        tvGiveAgent.setOnClickListener(v -> {
            SetPlusRateDialog dialog = SetPlusRateDialog.newInstance(type, device_no_list);
            dialog.show(getSupportFragmentManager(), "dialog");
            dialog.setOnCallBackListener(() -> {

            });
            popupLayout.dismiss();
        });
        tvGiveStore.setOnClickListener(v -> {
            GiveAgentDialog dialog1 = GiveAgentDialog.newInstance(type, "1", device_no_list);
            dialog1.show(getSupportFragmentManager(), "dialog");
            dialog1.setOnCallBackListener(() -> {
                refreshData();
            });
            popupLayout.dismiss();
        });


        //默认从底部弹出
        popupLayout.show();
    }

    private void initView() {
        refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);
        type = getIntent().getStringExtra("type");

        status = getIntent().getStringExtra("status");
        child_agent_id = getIntent().getStringExtra("child_agent_id");
        agent_name = getIntent().getStringExtra("agent_name");
        is_send = getIntent().getStringExtra("is_send");
        String titlePrefix = "";
        if (!TextUtils.isEmpty(agent_name)) {
            titlePrefix = agent_name + "_";
            if (agent_name.length() > 6) {
                titlePrefix = agent_name.substring(0, 6) + "_";
            }
        } else {
            titlePrefix = "";
        }

        if ("1".equals(type)) {
            titleBar.setTitle(titlePrefix + "云小宝");
        } else if ("2".equals(type)) {
            titleBar.setTitle(titlePrefix + "云商宝");
        } else if ("3".equals(type)) {
            titleBar.setTitle(titlePrefix + "云小宝Vip版");
        } else if ("4".equals(type)) {
            titleBar.setTitle(titlePrefix + "云小宝Plus版");
        }

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(keyword)) {
                        refreshData();
                    }
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = editSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initData() {
        String tag = "";
        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null) {
            agent_id = userInfoBean.getData().getId() + "";
        }
        if (agent_id.equals(child_agent_id)) {
            tag = "1";
        }
        homePageModel = new HomePageModelImpl();
        beanList = new ArrayList<>();
        listAdapter = new MachinesListAdapter(beanList, status, tag);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(listAdapter)
                .color(R.color.shimmer_color_1)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_machines_list)
                .show();

        requestData();
        //0未激活 1已激活
        if ("0".equals(status)) {
            if (agent_id.equals(child_agent_id)) {
                tv_implement_operation.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
            } else {
                tv_implement_operation.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
            }

            if ("5".equals(type)||"6".equals(type)){
                tv_implement_operation.setVisibility(View.GONE);
            }

        } else if ("1".equals(status)) {
            if (agent_id.equals(child_agent_id)) {
                tv_implement_operation.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
            } else {
                tv_implement_operation.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
            }
        } else {
            tv_implement_operation.setVisibility(View.GONE);
            llCheck.setVisibility(View.GONE);
        }
    }




    public void requestData() {
        homePageModel.requestDeviceUnifyReceivedList("0", is_send, page, child_agent_id, status, type, "no", keyword, new DataCallBack<DeviceUnifyListBean>() {
            @Override
            public void onSuccessful(DeviceUnifyListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }

            @Override
            public void onFailed(String msg, String code) {
                listAdapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestData();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestData();
        refreshLayout.finishRefresh(30000);
        allSelect = false;
        ivCheck.setImageResource(R.mipmap.ic_order_kongyuan);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(mActivity, "扫描取消", Toast.LENGTH_LONG).show();
            } else {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                String code = scanResult.getContents();
                EventBus.getDefault().post(new ScanEvent(code));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick({ R.id.view_cancel, R.id.tv_search, R.id.ll_check})
    public void onViewClicked(View view) {
        List<String> device_no_list = new ArrayList<>();
        List<String> store_number_list = new ArrayList<>();
        for (DeviceUnifyListBean.DataBean.ItemListBean itemListBean : beanList) {
            if (itemListBean.isCheck()) {
                device_no_list.add(itemListBean.getNo());
                store_number_list.add(itemListBean.getMem_no());
            }
        }
        switch (view.getId()) {
            case R.id.view_cancel:
                editSearch.setText("");
                keyword = "";
                refreshData();
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(keyword)) {
                    ToastUtil.showShort("请输入搜索内容");
                    return;
                }
                refreshData();
                break;
            case R.id.ll_check:
                if (!allSelect) {
                    for (DeviceUnifyListBean.DataBean.ItemListBean itemListBean : beanList) {
                        itemListBean.setCheck(true);
                    }
                    ivCheck.setImageResource(R.mipmap.ic_order_xuanze);
                    listAdapter.notifyDataSetChanged();
                } else {
                    for (DeviceUnifyListBean.DataBean.ItemListBean itemListBean : beanList) {
                        itemListBean.setCheck(false);
                    }
                    listAdapter.notifyDataSetChanged();
                    ivCheck.setImageResource(R.mipmap.ic_order_kongyuan);
                }
                allSelect = !allSelect;
                break;
        }
    }
}
